package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 * @RestControllerAdvice 这个注解包含了@ResponseBody 所以对象可以直接返回给前端
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 处理当用户名重复的时候的异常
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result exceptionHandler(SQLIntegrityConstraintViolationException sqlIntegrityConstraintViolationException) {
        // Duplicate entry '3348578419' for key 'employee.idx_username' 找出用户名
        String error = sqlIntegrityConstraintViolationException.getMessage() ;
        if (error.contains("Duplicate entry")) {
            String username = error.split(" ")[2] ;
            String message = username + MessageConstant.ALERADY_EXISTS ;
            return Result.error(message) ;
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

    }

}
